<?php

/**
 * corporatemanaged actions.
 *
 * @package    digitalform
 * @subpackage corporatemanaged
 * @author     Saul Santiago
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class corporatemanagedActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->tableColumns = ApplicationCorporateManagedTable::TableColumns();
  }

	public function executeAjaxdata(sfWebRequest $request) {
		sfConfig::set('sf_web_debug', false);
		$this->getResponse()->setContentType('application/json');
		$this->application_corporate_managed = Doctrine::getTable('ApplicationCorporateManaged');
		$json = $this->application_corporate_managed->fetchData($request);
		return $this->renderText($json);
	}

  public function executeAjaxNewForm(sfWebRequest $request) {
    sfConfig::set('sf_web_debug', false);
    $form = new ApplicationCorporateManagedForm();
    $assigneeForm = new AssigneeForm();
    return $this->renderPartial("applicationForm", array("form"=>$form, "assigneeForm" => $assigneeForm));
  }

  public function executeAjaxSave(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    sfConfig::set('sf_web_debug', false);
    $this->getResponse()->setContentType('application/json');
    $this->form = new ApplicationCorporateManagedForm();
    $data_array = $this->processForm($request, $this->form, 'Added new');
    return $this->renderText(json_encode($data_array));
  }

	public function executeAjaxEditForm(sfWebRequest $request) {
		$data = Doctrine_Core::getTable('ApplicationCorporateManaged')->findOneById($request->getParameter('id'));
		$form = new ApplicationCorporateManagedForm($data);
		return $this->renderPartial("applicationForm", array("form" => $form));
	}

  public function executeAssigneeslist(sfWebRequest $request)
  {
    $this->forward404Unless($application_id = $request->getParameter('appId'));
    sfConfig::set('sf_web_debug', false);
    $this->appId = $application_id;
    $this->assignees = AssigneeTable::getAssignees($application_id);
    return $this->renderPartial('assigneeslist',array('appId'=>$this->appId,'assignees'=>$this->assignees));
  }

  private function processForm(sfWebRequest $request, sfForm $form, $action)
  {
    $form->bind($request->getParameter($form->getName()));
    if ($form->isValid()) {
      try {
        $application = $form->save();
        $id = $application->getId();
        $data_arr = array("valid" => 'true', "message" => 'Data successfully saved!', "id" => $id);
        $log = new UserLogs();
        $log->setUserId($this->getUser()->getGuardUser()->getId());
        $log->setAction($action.' Corporate Managed application with Reference No.: '.$application->getRefNumber());
        $log->save();
      }
      catch (Exception $exc) {
        $data_arr = array("valid" => 'false', "message" => $exc->getMessage());
      }
    }
    else {
      $errors = $form->getErrorSchema()->getErrors();
      $errorText = '';
      foreach($errors as $key=>$val) {
        $errorText .= $key.': '.$val.'|';
      }
      $data_arr = array("valid" => 'false', "message" => $errorText);
    }
    return $data_arr;
  }

  public function executeDatadump(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $params['from'] = ($request->getPostParameter('date_from') != '') ? $request->getPostParameter('date_from') : '';
    $params['to'] = ($request->getPostParameter('date_to') != '') ? $request->getPostParameter('date_to') : '';
    $params['ref_number'] = ($request->getPostParameter('ref_number') != '') ? $request->getPostParameter('ref_number') : '';
    $params['first_name'] = ($request->getPostParameter('first_name') != '') ? $request->getPostParameter('first_name') : '';
    $params['last_name'] = ($request->getPostParameter('last_name') != '') ? $request->getPostParameter('last_name') : '';
    $params['status'] = ($request->getPostParameter('status') != '') ? $request->getPostParameter('status') : '';

    $data = Doctrine_Core::getTable("ApplicationCorporateIndividual")->getApplicationData($params);

    if(!empty($data)) {

      header('Content-Type: text/plain');
      header('Content-Disposition: attachment;filename="ApplicationReport.xls"');
      header('Cache-Control: max-age=0');

      foreach($data as $k=>$i) {
        unset($i['updated_at']);
        if($k == 0) {
            foreach(array_keys($i) as $field) {
              echo $field."\t";
            }
            echo "\r\n";
        }
        foreach($i as $key=>$val) {
          echo $val."\t";
        }
        echo "\r\n";
      }
    }
    else {
      echo "No data to dump!";
    }
    exit();

  }


	/** added by rommel m. zamora
	 * dynamic embedding of forms*/

	   public function executeAddAssignee(sfWebRequest $request) {

        $this->forward404Unless($product = Doctrine_Core::getTable('ApplicationCorporateManaged')->find(array($request->getParameter('id'))), sprintf('Object ApplicationCorporateManaged does not exist (%s).', $request->getParameter('id')));
        $this->form = new ApplicationCorporateManagedForm($product);
        $this->form->setAssignees(Doctrine_Core::getTable('Assignee')->getAssigneeByApplicationId(array($request->getParameter('id'))));
    }

    public function executeInsertAssignee(sfWebRequest $request) {
        $this->forward404unless($request->isXmlHttpRequest());
        $this->forward404Unless($assginee = Doctrine_Core::getTable('ApplicationCorporateManaged')->find(array($request->getParameter('id'))), sprintf('Object ApplicationCorporateManaged does not exist (%s).', $request->getParameter('id')));
        $this->getResponse()->setContentType('application/json');
        $this->form = new ApplicationCorporateManagedForm($assginee);
        // $data_array = $this->updateInventory($request, $this->form, $assginee);
        // return $this->renderText(json_encode($data_array));
    }

    public function executeUpdate(sfWebRequest $request) {
        $this->forward404unless($request->isXmlHttpRequest());
        $this->forward404Unless($application = Doctrine_Core::getTable('ApplicationCorporateManaged')->find(array($request->getParameter('id'))), sprintf('Object ApplicationCorporateManaged does not exist (%s).', $request->getParameter('id')));
        $this->getResponse()->setContentType('application/json');
        $this->form = new ApplicationCorporateManagedForm($application);
        $data_array = $this->processForm($request, $this->form, 'Updated');
        /**
         * Hack for Doctrine error on relation deletion within form.
         * For the meantime no error checking.
         *
         * note by: rommel m. zamora
         */
        $this->deleteAssigneeMarkedForDeletion($this->form->getAssigneesForDeletion());
        return $this->renderText(json_encode($data_array));
    }

    public function executeDelete(sfWebRequest $request) {
        $this->forward404unless($request->isXmlHttpRequest());
        sfConfig::set('sf_web_debug', false);
        $this->getResponse()->setContentType('application/json');
        $this->forward404Unless($assginee = Doctrine_Core::getTable('ApplicationCorporateManaged')->find(array($request->getParameter('id'))), sprintf('Object ApplicationCorporateManaged does not exist (%s).', $request->getParameter('id')));
        //$deleteAssignees = Doctrine_Query::create()->delete('Assignee')->where('application_id = ?',$request->getParameter('id'))->execute();
        try {
          $assginee->delete();
          $log = new UserLogs();
          $log->setUserId($this->getUser()->getGuardUser()->getId());
          $log->setAction('Deleted Corporate Managed application with Reference No.: '.$assginee->getRefNumber());
          $log->save();
          $data_arr = array("valid" => 'true', "message" => 'Data was successfully deleted!');
        }
        catch (Exception $exc) {
          $data_arr = array("valid" => 'false', "message" => $exc->getMessage());
        }
        return $this->renderText(json_encode($data_arr));

    }

    /**
     * Dynamiclly embed relation (Assignee) from
     *
     * @param sfWebRequest $request
     * @return String
     */
    public function executeAddAssigneeForm(sfWebRequest $request)
    {
      $this->forward404unless($request->isXmlHttpRequest());
      $number = intval($request->getParameter("num"));
      if ($assignee = Doctrine_Core::getTable('ApplicationCorporateManaged')->find(array($request->getParameter('id')))) {
        $form = new ApplicationCorporateManagedForm($assignee);
      } else {
        $form = new ApplicationCorporateManagedForm(null);
      }
      $form->addAssignees($number);

      return $this->renderPartial('addAssignee',array('form' => $form, 'num' => $number));
    }

    protected function deleteAssigneeMarkedForDeletion($values = null) {
        /**
         * traverse all assignees marked for deletion
         */
        if (count($values)) {
            foreach ($values as $index => $id) {
                Doctrine::getTable('Assignee')->find($id)->delete();
            }
        }
    }


}
